<?php
/**
 * The Route class.
 *
 */
class Route {
    /**
     * The route regex.
     * @var string
     */
    protected $route;
    /**
     * The class to instantiate for this route.
     * @var string
     */
    protected $class;
    /**
     * The method to call.
     * @var string
     */
    protected $method;
    /**
     * A map to workout which parameter is which.
     * @var array
     */
    protected $parammap;
    /**
     * The parameters obtained from the URL.
     * @var array
     */
    protected $params = array();
    
    /**
     * The constructor.
     * 
     * Parse the route and build the regex and parameter map.
     * @param string $route
     * @param string $class
     * @param string $method
     */
    public function __construct($route, $class, $method) {
        $matches = array();
        $parammap = array();
        $nummatches = preg_match_all('/\((.+?):(str|int)\)?/', $route, $matches);
        if($nummatches > 0) {
            for($i = 0; $i < $nummatches; $i++) {
                switch($matches[2][$i]) {
                    case 'int':
                        $replace = '(\d+)';
                        break;
                    case 'str':
                    default:
                        $replace = '(.+)';
                        break;
                }
                $route = str_replace($matches[0][$i], $replace, $route);
                $parammap[] = $matches[1][$i];   
            }
        }
        $route = '|^' . $route . '/{0,1}$|';
        $this->route = $route;
        $this->class = $class;
        $this->parammap = $parammap;
        $this->method = $method;
    }
    
    /**
     * Get the route.
     * @return string
     */
    public function getRoute() {
        return $this->route;
    }

    /**
     * Get the class name.
     * @return string
     */
    public function getClass() {
        return $this->class;
    }

    /**
     * Get the method name.
     * @return string
     */
    public function getMethod() {
        return $this->method;
    }
    
    /**
     * Get the parameters.
     * @return array
     */
    public function getParams() {
        return $this->params;
    }
    
    /**
     * Check the route against the URL to see is it matches. If it does generate the parameter array.
     * @param string $url
     * @return bool
     */
    public function checkRoute($url) {
        $matches = array();
        $nummatches = preg_match_all($this->route, $url, $matches, PREG_SET_ORDER);
        if($nummatches > 0) {
            $matches = $matches[0];
            array_shift($matches);
            foreach($matches as $key=>$value) {
                $this->params[$this->parammap[$key]] = urldecode($value);
            }
            return true;
        }
        return false;
    }
}
?>